﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FzWeb.Models
{
    /// <summary>
    /// 处理用户数据
    /// </summary>
    public class UserService
    {
        public Entities db
        {
            get
            {
                if (HttpContext.Current.Session["db"] == null)
                {
                    HttpContext.Current.Session["db"] = new Entities();
                }
                return HttpContext.Current.Session["db"] as FzWeb.Models.Entities;
            }
        }

        public void Register(User user)
        {
            db.AddToUser(user);
            db.SaveChanges();
        }

        public IList<User> GetUserList(Func<User, bool> predict)
        {
            return db.User.Include("role").Where(predict).ToList();
        }

        public IList<User> GetUserList()
        {
            return db.User.Include("role").Include("person").Include("company").ToList();
        }

        public User GetUser(int id)
        {
            return db.User.Include("role").Include("person").Include("company").First(c => c.UserId == id);
        }

        public User GetUser(Func<User,bool> prefict)
        {
            return db.User.Include("role").Include("person").Include("company").First(prefict);
        }

        /// <summary>
        /// 获得user的所有相关数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public User GetUserAll(int id)
        {
            return db.User.Include("role").Include("role.module").Include("person").Include("company").First(c => c.UserId == id);
        }

        public Person GetPersonAll(int id)
        {
            return db.Person.Include("person_resume").Include("Person_Job_History").
               Include("person_search").Include("user").First(c=>c.PersonId==id);
        }

        public void UpdateUser(User user)
        {
            db.ApplyPropertyChanges(GetUser(user.UserId).EntityKey.EntitySetName, user);
            db.SaveChanges();
        }

        public void AddAdmin(User user)
        {
            db.AddToUser(user);
            db.SaveChanges();
        }

        public void DelUser(int id)
        {
            db.DeleteObject(GetUser(id));
            db.SaveChanges();
        }
    }
}
